package com.yyplatform.admin.platform.config.service.impl;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yyplatform.admin.platform.config.model.dto.SysConfigSwiperDTO;
import com.yyplatform.admin.platform.config.model.dto.SysConfigSwiperFormDTO;
import com.yyplatform.admin.platform.config.model.dto.SysConfigSwiperQueryDTO;
import com.yyplatform.admin.platform.config.model.entity.SysConfigSwiperEntity;
import com.yyplatform.admin.platform.config.model.SwiperDTO;
import com.yyplatform.admin.platform.config.repository.SysConfigSwiperRepository;
import com.yyplatform.admin.platform.config.service.SysConfigSwiperService;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.exception.ServiceException;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-11-25
 */
@Service
@Slf4j
@AllArgsConstructor
public class SysConfigSwiperServiceImpl implements SysConfigSwiperService {

    private SysConfigSwiperRepository sysConfigSwiperRepository;


    @Override
    public Page<SysConfigSwiperDTO> listAll(SysConfigSwiperQueryDTO queryDTO) {
        Page<SysConfigSwiperEntity> page = sysConfigSwiperRepository.findAll(queryDTO.getPageRequest());


        List<SysConfigSwiperDTO> dtoList = page.stream().map(this::toDTO).toList();
        return new PageImpl<>(dtoList, queryDTO.getPageRequest(), page.getTotalElements());
    }


    private SysConfigSwiperDTO toDTO(SysConfigSwiperEntity e) {
        SysConfigSwiperDTO dto = new SysConfigSwiperDTO();
        dto.setId(e.getId());
        dto.setRemark(e.getRemark());
        dto.setSwiperKey(e.getSwiperKey());


        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<SwiperDTO> list = objectMapper.readValue(e.getJsonData(), new TypeReference<>() {
            });
            dto.setSwiperList(list);
        } catch (JsonProcessingException ex) {
            log.error("json processiong ex", ex);
            throw ServiceException.of(ErrorCode.INTERNAL_SERVER_ERROR, "json 解析错误");
        }


        return dto;
    }


    @Override
    public SysConfigSwiperDTO get(Long id) {
        SysConfigSwiperEntity sysConfigSwiperEntity = sysConfigSwiperRepository.getReferenceById(id);
        return toDTO(sysConfigSwiperEntity);
    }


    @Override
    public void delete(Long id) {
        sysConfigSwiperRepository.deleteById(id);
    }

    @Override
    public void save(SysConfigSwiperFormDTO dto) {
        checkParam(dto);


        SysConfigSwiperEntity entity = new SysConfigSwiperEntity();
        entity.setSwiperKey(dto.getSwiperKey());
        entity.setRemark(dto.getRemark());
        entity.setJsonData(dto.getSwiperListJson());


        sysConfigSwiperRepository.save(entity);
    }


    @Override
    public void update(SysConfigSwiperFormDTO dto) {

        checkParam(dto);

        SysConfigSwiperEntity entity = sysConfigSwiperRepository.getReferenceById(dto.getId());

        entity.setRemark(dto.getRemark());
        entity.setJsonData(dto.getSwiperListJson());

        sysConfigSwiperRepository.save(entity);

    }

    @Override
    public List<SwiperDTO> getSwiperList(String key) {
        SysConfigSwiperEntity entity = sysConfigSwiperRepository.findBySwiperKey(key);


        if (entity == null || StringUtils.isEmpty(entity.getJsonData())) {
            return Collections.emptyList();
        }

        String json = entity.getJsonData();

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            log.error("json processiong ex", e);
            throw ServiceException.of(ErrorCode.INTERNAL_SERVER_ERROR, "json 解析错误");
        }

    }


    private void checkParam(SysConfigSwiperFormDTO dto) {

        String json = dto.getSwiperListJson();

        if (StringUtils.isEmpty(json)) {
            throw ServiceException.of(ErrorCode.PARAM_INVALID, "轮播图配置不能为空");
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<SwiperDTO> list = objectMapper.readValue(json, new TypeReference<>() {
            });

            for (SwiperDTO swiperDTO : list) {
                if (StringUtils.isEmpty(swiperDTO.getIndex()) || StringUtils.isEmpty(swiperDTO.getFaceUrl())
                        || StringUtils.isEmpty(swiperDTO.getLinkUrl())) {
                    throw ServiceException.of(ErrorCode.PARAM_INVALID,
                            "轮播图配置格式异常，index、faceUrl和linkUrl不能为空值.");
                }
            }
        } catch (JsonProcessingException ex) {
            log.error("json processiong ex", ex);
            throw ServiceException.of(ErrorCode.PARAM_INVALID, "轮播图配置格式异常，不是合法json值.");
        }
    }


}
